package com.shawn.spring.boot.mybatis.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.shawn.spring.boot.mybatis.entity.User;
import com.shawn.spring.boot.mybatis.entity.UserExample;
import com.shawn.spring.boot.mybatis.mapper.UserMapper;
import com.shawn.spring.boot.mybatis.service.UserService;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

/**
 * @author shawn
 * @since 2020/8/30
 */
@Service
public class UserServiceImpl implements UserService {

  @Autowired private UserMapper userMapper;

  @Override
  public void register(User user) {
    Date now = Calendar.getInstance().getTime();
    user.setCreateTime(now);
    user.setUpdateTime(now);
    user.setIsDeleted(0);
    int id = userMapper.insert(user);
    userMapper.insertUserRole(1, id);
  }

  @Override
  public User login(String username, String password) {
    UserExample example = new UserExample();
    example.createCriteria().andUsernameEqualTo(username).andPasswordEqualTo(password);
    List<User> users = userMapper.selectByExample(example);
    if (CollectionUtils.isEmpty(users) || users.size() > 1) {
      throw new IllegalStateException("login failed!");
    }
    return users.get(0);
  }

  @Override
  public PageInfo<User> findWithPageHelper(int pageNum, int pageSize) {
    PageHelper.startPage(pageNum, pageSize);
    List<User> userList = userMapper.selectAll();
    PageInfo<User> pageInfo = new PageInfo(userList);
    return pageInfo;
  }

  @Override
  public PageInfo<User> findWithRowBounds(int pageNum, int pageSize) {
    List<User> users = userMapper.selectWithRowBounds(new RowBounds(pageNum, pageSize));
    PageInfo<User> pageInfo = new PageInfo(users);
    return pageInfo;
  }

  @Override
  public PageInfo<User> findWithParams(int pageNum, int pageSize) {
    List<User> users = userMapper.selectWithParams(pageNum, pageSize);
    PageInfo<User> pageInfo = new PageInfo(users);
    return pageInfo;
  }
}
